package com.xxx.springboot.service.impl;

import java.util.concurrent.TimeUnit;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;

import com.xxx.springboot.service.DistributedLocker;

/**
 * 【redisson分布式锁】2.Redisson 分布式锁接口实现类
 * https://www.cnblogs.com/yangzhilong/p/7605807.html
 */
public class RedissonDistributedLocker implements DistributedLocker {
	
	private RedissonClient redissonClient;

	@Override
	public RLock lock(String lockKey) {
		RLock lock = redissonClient.getLock(lockKey);
		lock.lock();
		return lock;
	}

	@Override
	public RLock lock(String lockKey, int leaseTime) {
		RLock lock = redissonClient.getLock(lockKey);
		lock.lock(leaseTime, TimeUnit.SECONDS);
		return lock;
	}

	@Override
	public RLock lock(String lockKey, TimeUnit timeunit, int leaseTime) {
		RLock lock = redissonClient.getLock(lockKey);
		lock.lock(leaseTime, timeunit);
		return lock;
	}

	@Override
	public boolean tryLock(String lockKey, TimeUnit unit, int waitTime, int leaseTime) {
		RLock lock = redissonClient.getLock(lockKey);
		try {
			boolean result = lock.tryLock(waitTime, leaseTime, unit);
			return result;
		} catch (InterruptedException e) {
			return false;
		}
	}

	@Override
	public void unLock(String lockKey) {
		RLock lock = redissonClient.getLock(lockKey);
		lock.unlock();
	}

	@Override
	public void unLock(RLock lock) {
		lock.unlock();
	}

	// setter注入redissonClient
	public void setRedissonClient(RedissonClient redissonClient) {
        this.redissonClient = redissonClient;
    }
	
}
